package com.dm0858.bianmin.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.app.MyApp;
import com.dm0858.bianmin.databinding.ActivityShangjiaDetailBinding;
import com.dm0858.bianmin.mine.listener.IResultListener;
import com.dm0858.bianmin.mine.model.MineModel;
import com.dm0858.bianmin.mine.network.Retrofit;
import com.dm0858.bianmin.mine.tools.LogUtils;
import com.dm0858.bianmin.mine.tools.ToastUtils;
import com.dm0858.bianmin.model.entity.NewsRecord;
import com.dm0858.bianmin.model.entity.ShangJia;
import com.dm0858.bianmin.model.entity.ShangJiaData;
import com.dm0858.bianmin.model.response.ShangJiaResponse;
import com.dm0858.bianmin.ui.base.BaseActivity;
import com.dm0858.bianmin.ui.presenter.ShangJiaPresenter;
import com.dm0858.bianmin.view.IShangJiaView;
import com.dm0858.uikit.TipView;
import com.google.gson.Gson;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.socks.library.KLog;
import com.sunfusheng.glideimageview.progress.GlideApp;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.dm0858.bianmin.app.ApiConstant.BASE_SERVER_URL;

/**
 * Created by yelvqing on 2017/11/28.
 */

public class ShangJiaActivity  extends BaseActivity<ShangJiaPresenter> implements IShangJiaView ,CheckBox.OnCheckedChangeListener{

    private ActivityShangjiaDetailBinding binding;

    public static final String id = "0";
    @Bind(R.id.iv_back)
    ImageView mIvBack;

    @Bind(R.id.normal_listtitle)
    TextView mtitle;

    @Bind(R.id.normal_title)
    TextView mtitle2;

    @Bind(R.id.tip_view)
    TipView mTipView;

    @Bind(R.id.rollPage)
    RollPagerView mRollViewPager;

    @Bind(R.id.normal_calltxt)
    TextView mcall;


    @Bind(R.id.normal_addrtxt)
    TextView maddr;
    @Bind(R.id.normal_liulan)
    TextView normal_liulan;


    @Bind(R.id.normal_addr)
    TextView normal_addr;

    @Bind(R.id.callbtn)
    Button callaction;

    @Bind(R.id.normal_rztxt)
    TextView mbeian;


    @Bind(R.id.webView)
    WebView mcontent;

    @Bind(R.id.normal_call_layout)
    LinearLayout normal_call_layout;

    @Bind(R.id.normal_renzheng_layout)
    LinearLayout normal_renzheng_layout;

    @Bind(R.id.zufang_shuxing_layout)
    LinearLayout zufang_shuxing_layout;

    @Bind(R.id.hengxian1)
    View hengxian1;

    @Bind(R.id.hengxian2)
    View hengxian2;

    @Bind(R.id.hengxian3)
    View hengxian3;

    @Bind(R.id.shuxing_line1)
    View shuxing_line1;

    @Bind(R.id.shuxing_line2)
    View shuxing_line2;
    @Bind(R.id.shuxing_line3)
    View shuxing_line3;
    @Bind(R.id.shuxing_line4)
    View shuxing_line4;

    @Bind(R.id.zf_diqu_layout)
    LinearLayout zf_diqu_layout;

    @Bind(R.id.fangyuan_miaoshu)
    TextView fangyuan_miaoshu;

    @Bind(R.id.cheliang_miaoshu)
    TextView cheliang_miaoshu;

    @Bind(R.id.normal_fuwuneirong)
    TextView normal_fuwuneirong;

    //zf
    @Bind(R.id.zf_diqu)
    TextView zf_diqu;
    @Bind(R.id.zf_huxing)
    TextView zf_huxing;
    @Bind(R.id.zf_jiage)
    TextView zf_jiage;
    @Bind(R.id.zf_mianji)
    TextView zf_mianji;

    //esc
    @Bind(R.id.ershouche_shuxing_layout)
    LinearLayout ershouche_shuxing_layout;
    @Bind(R.id.esc_chexing)
    TextView esc_chexing;
    @Bind(R.id.esc_jiage)
    TextView esc_jiage;
    @Bind(R.id.esc_licheng)
    TextView esc_licheng;
    @Bind(R.id.esc_pl)
    TextView esc_pl;
    @Bind(R.id.esc_shangpai)
    TextView esc_shangpai;
    @Bind(R.id.esc_shangpai_layout)
    LinearLayout esc_shangpai_layout;
    @Bind(R.id.shuxing_line5)
    View shuxing_line5;
    @Bind(R.id.normal_addr_layout)
    LinearLayout normal_addr_layout;
    @Bind({R.id.checkbox})
    CheckBox checkBox;



    @Override
    protected ShangJiaPresenter createPresenter() {
        return new ShangJiaPresenter(this);
    }


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_shangjia_detail;
    }

    //记录
    private NewsRecord mNewsRecord;

    private List<ShangJiaData> mNewsList = new ArrayList<>();
    protected BaseQuickAdapter mNewsAdapter;

    /**
     * 是否是点击底部标签进行刷新的标识
     */
    private boolean isClickTabRefreshing;
    private RotateAnimation mRotateAnimation;
    private Gson mGson = new Gson();


    protected String mid;
    protected String mtel;
    private int position;

    private Retrofit retrofit;

    private List<String> imgs= new ArrayList<String>();

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

        if (retrofit == null) retrofit = new Retrofit();
        Intent intent = getIntent();

        mid = intent.getStringExtra(id);
        String lat = intent.getStringExtra("lat");
        String lng = intent.getStringExtra("lng");
        String addr = intent.getStringExtra("addr");
        position = intent.getIntExtra("position",-1);

        KLog.e("mid=" + mid);
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().url(BASE_SERVER_URL+"phpapi/info.php?func=updateClickNum&tid="+mid)
                .get().build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Fail");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

//                System.out.println(response.body().string());

            }
        });

        mPresenter.getShangJia(mid);

        normal_addr_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转

                //  com.baidu.BaiduMap这是高德地图的包名
                //调起百度地图客户端try {
                Intent intent = new Intent();


                intent.setData(Uri.parse("baidumap://map/marker?location="
                        + lat + "," + lng + "&title="+ addr +"&content=&traffic=on&src=andr.baidu.openAPIdemo"));


                if(isInstallByread("com.baidu.BaiduMap")){
                    ShangJiaActivity.this.startActivity(intent); //启动调用
                    Log.e("GasStation", "百度地图客户端已经安装") ;

                }else{

                    if(isInstallByread("com.autonavi.minimap")){
                        Log.e("GasStation", "高德地图客户端已经安装") ;
                        goToGaode(lat,lng);
                    }else{
                        Toast.makeText(ShangJiaActivity.this, "没有安装地图客户端", Toast.LENGTH_SHORT).show();
                    }
                }
            }

        });
    }

    //高德
    private void goToGaode(String lat, String lon) {

        CoordinateConverter converter  = new CoordinateConverter(this);
// CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
// sourceLatLng待转换坐标点 DPoint类型
        try {
            converter.coord(new DPoint(Double.parseDouble(lat),Double.parseDouble(lon)));
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "解析经纬度出错", Toast.LENGTH_SHORT).show();

            return;
        }
// 执行转换操作
        DPoint desLatLng;

        try {
            desLatLng = converter.convert();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "解析经纬度出错", Toast.LENGTH_SHORT).show();
            return;
        }

        StringBuffer stringBuffer = new StringBuffer("androidamap://route?sourceApplication=").append("amap");

        stringBuffer.append("&dlat=").append(desLatLng.getLatitude())
                .append("&dlon=").append(desLatLng.getLongitude())
                .append("&dname=").append("")
                .append("&dev=").append(0)
                .append("&t=").append(0);

        Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
        intent.setPackage("com.autonavi.minimap");
        this.startActivity(intent);
    }





    /**
     * 判断是否安装目标应用
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }


    @Override
    public void initListener() {



        mcall.setOnClickListener(view->callTel());
        callaction.setOnClickListener(view->callTel());


    }

    public  void callTel()
    {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+mtel));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }



    int collectFlag;

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (MyApp.launchMode == 1) {
            if (shangJiaResponse.data.collectFlag == 0) collectFlag = 1;
            else if (shangJiaResponse.data.collectFlag == 1) collectFlag = 0;
            MineModel.collectArticleAction(retrofit,MyApp.userid, mid, collectFlag, object -> {
                if (shangJiaResponse.data.collectFlag == 0) {
                    ToastUtils.showShort("收藏成功");
                    shangJiaResponse.data.collectFlag = 1;
                    setResult(1003);
                }
                else {

                    ToastUtils.showShort("取消收藏");
                    shangJiaResponse.data.collectFlag = 0;
                    Intent intent = new Intent();
                    intent.putExtra("position",position);
                    setResult(1001,intent);

                }
            });
        }
    }

    private class TestNormalAdapter extends StaticPagerAdapter {
        private int[] imgs2 = {
                R.mipmap.a1,
                R.mipmap.a2,
        };


        @Override
        public View getView(ViewGroup container, int position) {
            ImageView view = new ImageView(container.getContext());

            //  view.setImageResource(imgs2[position]);
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            GlideApp.with(container.getContext()).load(imgs.get(position)).into(view);
            return view;



        }


        @Override
        public int getCount() {

            return imgs.size();
        }
    }

    private ShangJiaResponse shangJiaResponse;

    @Override
    public void onGetShangJiaSuccess(ShangJiaResponse shangJiaResponse) {

        this.shangJiaResponse = shangJiaResponse;

            String[] all=shangJiaResponse.data.fengmian.split(",");
            for (int i=0;i<all.length;i++){
                imgs.add(all[i]);
                KLog.e("ekod="+all[i]);

            }



        //设置播放时间间隔
        mRollViewPager.setPlayDelay(15000);
        //设置透明度
        mRollViewPager.setAnimationDurtion(500);
        //设置适配器
        mRollViewPager.setAdapter(new ShangJiaActivity.TestNormalAdapter());

        //设置指示器（顺序依次）
        //自定义指示器图片
        //设置圆点指示器颜色
        //设置文字指示器
        //隐藏指示器
        //mRollViewPager.setHintView(new IconHintView(this, R.drawable.point_focus, R.drawable.point_normal));
        mRollViewPager.setHintView(new ColorPointHintView(this, Color.RED, Color.WHITE));
        //mRollViewPager.setHintView(new TextHintView(this));
        //mRollViewPager.setHintView(null);


        String type = shangJiaResponse.data.type;
        if (shangJiaResponse.data.collectFlag == 1) checkBox.setChecked(true);
        else if (shangJiaResponse.data.collectFlag == 0) checkBox.setChecked(false);
        checkBox.setOnCheckedChangeListener(this);
        switch (type)
        {
            case "normal":
            {
                mtitle2.setText(shangJiaResponse.data.title);

                mcall.setText(shangJiaResponse.data.tel);
                maddr.setText(shangJiaResponse.data.addr);

                mbeian.setText(shangJiaResponse.data.beian);

                break;
            }
            case "zufang":
            {
                mtitle2.setText(shangJiaResponse.data.title);

                mcall.setText(shangJiaResponse.data.tel);
                maddr.setText(shangJiaResponse.data.xiaoqu);
                normal_renzheng_layout.setVisibility(View.GONE);

                zufang_shuxing_layout.setVisibility(View.VISIBLE);
                hengxian1.setVisibility(View.GONE);
                hengxian2.setVisibility(View.GONE);
                hengxian3.setVisibility(View.GONE);
                shuxing_line1.setVisibility(View.VISIBLE);
                shuxing_line2.setVisibility(View.VISIBLE);
                shuxing_line3.setVisibility(View.VISIBLE);
                shuxing_line4.setVisibility(View.VISIBLE);

                zf_diqu_layout.setVisibility(View.VISIBLE);
                normal_addr.setText("小区");
                fangyuan_miaoshu.setVisibility(View.VISIBLE);
                normal_fuwuneirong.setVisibility(View.GONE);

                zf_diqu.setText(shangJiaResponse.data.addr);
                zf_huxing.setText(shangJiaResponse.data.huxing);
                zf_jiage.setText(shangJiaResponse.data.jiage);
                zf_mianji.setText(shangJiaResponse.data.mianji);

                break;
            }
            case "ershouche":
            {

                normal_renzheng_layout.setVisibility(View.GONE);
                hengxian1.setVisibility(View.GONE);
                hengxian2.setVisibility(View.GONE);
                hengxian3.setVisibility(View.GONE);
                cheliang_miaoshu.setVisibility(View.VISIBLE);


                ershouche_shuxing_layout.setVisibility(View.VISIBLE);
                hengxian1.setVisibility(View.GONE);
                hengxian2.setVisibility(View.GONE);
                hengxian3.setVisibility(View.GONE);
                shuxing_line1.setVisibility(View.VISIBLE);
                shuxing_line2.setVisibility(View.VISIBLE);
                shuxing_line3.setVisibility(View.VISIBLE);
                shuxing_line4.setVisibility(View.VISIBLE);
                shuxing_line5.setVisibility(View.VISIBLE);
                normal_fuwuneirong.setVisibility(View.GONE);
                esc_shangpai_layout.setVisibility(View.VISIBLE);

                mtitle2.setText(shangJiaResponse.data.title);

                mcall.setText(shangJiaResponse.data.tel);
                normal_addr.setText("看车地址");
                maddr.setText(shangJiaResponse.data.addr);
                esc_shangpai.setText(shangJiaResponse.data.shangpai);
                esc_jiage.setText(shangJiaResponse.data.jiage);
                esc_chexing.setText(shangJiaResponse.data.chengxing);
                esc_licheng.setText(shangJiaResponse.data.licheng);
                esc_pl.setText(shangJiaResponse.data.pailiang);





                break;
            }
            default:
                break;
        }


        normal_liulan.setText("已有"+shangJiaResponse.data.clicknum+"人浏览");

        WebSettings webSettings = mcontent.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setJavaScriptEnabled(true);

        webSettings.setDomStorageEnabled(true);





        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        String baseUrl = "http://bmshfw.net/";
        String css = "<style type=\"text/css\"> img {" +
                "width:100%;" +
                "height:auto;" +
                "}" +

                "</style>";
        String html = "<html><header>" + css + "</header><body>" + shangJiaResponse.data.explain.toString() + "</body></html>";

        mcontent.loadDataWithBaseURL(baseUrl, html, "text/html" , "utf-8", null);


        mtel=shangJiaResponse.data.tel;
    }

    @Override
    public void onError() {
        mTipView.show();//弹出提示




    }

    @OnClick({R.id.iv_back,R.id.checkbox})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                setResult(1001);
                finish();
                break;
            case R.id.checkbox:
                if (MyApp.launchMode == -1) {
                    ToastUtils.showShort("您还未登录");
                    checkBox.setChecked(false);
                }
                else if (MyApp.launchMode == 2) {
                    ToastUtils.showShort("您还没有绑定手机号");
                    checkBox.setChecked(false);
                }

                break;
        }

    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

}


